//
//  MeViewController.swift
//  BellManage
//
//  Created by Bestsch on 16/4/1.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class MeViewController: BaseViewController, UITableViewDelegate,UITableViewDataSource, MBProgressHUDDelegate {
    
    var hud: MBProgressHUD!
    var tableView: UITableView!
    
    //1212 - 使用代码构写、不需要使用这个初始化
//    required init?(coder aDecoder: NSCoder) {
//        super.init(coder: aDecoder)
//        
//        self.tabBarItem.image = UIImage.init(named: "32meb")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
//        self.tabBarItem.selectedImage = UIImage.init(named: "32meg")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
//        self.tabBarItem.title = "我"
//        self.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor(hexString: "4e92df", alpha: 1)], for: UIControlState.selected)
//    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.title = "我"
        
        InitViews()
        
        NotificationCenter.default.addObserver(self, selector: #selector(MeViewController.MeClick(_:)), name: NSNotification.Name(rawValue: "MeClick"), object: nil)
    }
    
    func InitViews() {
        
        let user = getUserPojo()
        let header = UIView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: 120))
        header.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
        
        let view = UIView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: 100))
        view.backgroundColor = UIColor.white
        header.addSubview(view)
        
        let userTx = UIImageView.init(frame: CGRect(x: 20, y: 15, width: 70, height: 70))
        userTx.layer.masksToBounds = true
        userTx.layer.cornerRadius = 35
        userTx.image = UIImage.init(named: "touxiangm")
        view.addSubview(userTx)
        let username = UILabel.init(frame: CGRect(x: userTx.frame.maxX + 10, y: 15, width: screenW/2, height: 70))
        username.textColor = UIColor.darkGray
        username.font = UIFont.systemFont(ofSize: 16)
        username.textAlignment = NSTextAlignment.left
        username.text = user.username
        view.addSubview(username)
        
        let foot = UIView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: 1))
        foot.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
       
        tableView = UITableView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: screenH))
        tableView.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
        tableView.tableHeaderView = header
        tableView.tableFooterView = foot
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
        self.view.addSubview(tableView)
        
        let button: UIButton = UIButton.init(frame: CGRect(x: 30, y: self.view.frame.size.height - 50 - 50, width: screenW - 60, height: 40))
        button.layer.cornerRadius = 6
        button.backgroundColor = UIColor.init(red: 232/255, green: 10/255, blue: 30/255, alpha: 1)
        button.setTitle("注销", for: UIControlState())
        button.setTitleColor(UIColor.white, for: UIControlState())
        button.addTarget(self, action: #selector(MeViewController.buttonClick), for: UIControlEvents.touchDown)
        self.view.addSubview(button)
        
    }
    
    func buttonClick() {

        let alert = UIAlertController.init(title: "提示", message: "是否注销当前用户？", preferredStyle: UIAlertControllerStyle.alert)
        let noAction = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel, handler: nil)
        
        
        let yesAction = UIAlertAction(title: "注销", style: UIAlertActionStyle.default) { (action) in
            
            let defaults = UserDefaults.standard
            defaults.set("", forKey: "userphone")
            defaults.set("", forKey: "password")
            defaults.set("", forKey: "userid")
            defaults.set("", forKey: "username")
            defaults.set("", forKey: "usertype")
            defaults.set("", forKey: "schid")
            defaults.set("", forKey: "schname")
            defaults.set("", forKey: "doname")
            defaults.synchronize()
            //1229 - 在注销时候删除本地数据
            let store = YTKKeyValueStore(dbWithName: DBName)
            if (store?.isTableExists(tableName))! {
                store?.clearTable(tableName)
                store?.dropTable(tableName)
            }
            //++++++++++++++++++++++++++
            
            let myDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
            myDelegate.gotoLogin()
            
            
        }
        alert.addAction(noAction)
        alert.addAction(yesAction)
        self.present(alert, animated: true, completion: nil)
    }
    
    //MARK: - table View delegate and dataSource
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 50
    }
    /**
     多少行
     
     - parameter tableView: tableview
     - parameter section:
     
     - returns: 行数
     */
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 5
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cellIdentifier = "MeTableViewCellIdentifier";
        
        let cell: MeTableViewCell = MeTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
        cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
        cell.selectionStyle = UITableViewCellSelectionStyle.none;
        
        let count = (indexPath as NSIndexPath).row
        switch count {
        case 0:
            cell.icon.image = UIImage.init(named: "Lock")
            cell.title.text = "修改密码"
            break
        case 1:
            cell.icon.image = UIImage.init(named: "fankui")
            cell.title.text = "意见反馈"
            break
        case 2:
            cell.icon.image = UIImage.init(named: "uss")
            cell.title.text = "关于我们"
            break
        case 3:
            cell.icon.image = UIImage.init(named: "listlook")
            cell.title.text = "举报投诉"
            break
        case 4:
            cell.icon.image = UIImage.init(named: "lj")
            cell.title.text = "清理缓存"
            break
        default:
            break
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch (indexPath as NSIndexPath).row {
        case 0:
            /**
             *  修改密码
             */
            NotificationCenter.default.post(name: Notification.Name(rawValue: "MeClick"), object: nil, userInfo: ["target" : "修改密码"])
            break
        case 1:
            /**
             *  意见反馈
             */
            NotificationCenter.default.post(name: Notification.Name(rawValue: "MeClick"), object: nil, userInfo: ["target" : "意见反馈"])
            break;
        case 2:
            /**
             *  关于我们
             */
            NotificationCenter.default.post(name: Notification.Name(rawValue: "MeClick"), object: nil, userInfo: ["target" : "关于我们"])
            break;
        case 3:
            /**
             *  举报投诉
             */
            NotificationCenter.default.post(name: Notification.Name(rawValue: "MeClick"), object: nil, userInfo: ["target" : "举报投诉"])
            break;
        case 4:
            /**
             *  举报投诉
             */
            NotificationCenter.default.post(name: Notification.Name(rawValue: "MeClick"), object: nil, userInfo: ["target" : "清理缓存"])
            break;
        default:
            break;
        }
    }
    
    
    //MARK: - MEClick action
    
    func MeClick(_ notification: Notification) {
        let dic: NSDictionary = (notification as NSNotification).userInfo! as NSDictionary
        let target = dic.object(forKey: "target") as! String
        switch target {
        case "关于我们":
            let aboutUS = AboutUsViewController()
            aboutUS.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(aboutUS, animated: true)
            break
        case "意见反馈":
            let opinion = OpinionViewController()
            opinion.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(opinion, animated: true)
            break
        case "举报投诉":
            let report = ReportViewController()
            report.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(report, animated: true)
            break
        case "清理缓存":
            
            clearCacheAlert()
            
            break
        case "修改密码":
            
            changePassWordAlert()
            
            break
        default:
            break;
        }
    }
    
    //MARK: - clearCacheAlert
    
    func clearCacheAlert() {
        
        let alert = UIAlertController.init(title: "清理缓存", message: "缓存大小为\(String(format: "%.2f",getCachSize()))M,确定清理吗？", preferredStyle: UIAlertControllerStyle.alert)
        
        let noAction = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel, handler: nil)
        let yesAction = UIAlertAction(title: "确定", style: UIAlertActionStyle.default) { (action) in
            
            //1229 - 在注销时候删除本地数据
            let store = YTKKeyValueStore(dbWithName: DBName)
            if (store?.isTableExists(tableName))! {
                store?.clearTable(tableName)
                store?.dropTable(tableName)
            }
            //++++++++++++++++++++++++++
            
            self.hud = MBProgressHUD.showAdded(to: self.view, animated: true)
            self.hud.animationType = MBProgressHUDAnimation.fade
            self.hud.labelText = "正在清理缓存...请稍候"
            
            SDImageCache.shared().clearDisk(onCompletion: {
                self.hud.hide(true)
                self.hud = MBProgressHUD.showAdded(to: self.view, animated: true)
                self.hud.mode = MBProgressHUDMode.customView
                self.hud.labelText = "缓存已清理！";
                self.hud.customView = UIImageView.init(image: UIImage.init(named: "okbai"))
                DispatchQueue.global( priority: DispatchQueue.GlobalQueuePriority.low).async(execute: {
                    // Do something...
                    sleep(1);
                    DispatchQueue.main.async(execute: {
                        self.hud.hide(true)
                        
                    });
                });
                
            })
            
        }
        alert.addAction(noAction)
        alert.addAction(yesAction)
        self.present(alert, animated: true, completion: nil)
    }
    
    func getCachSize() -> CGFloat {
        
        let cachSize = CGFloat(SDImageCache.shared().getSize())/CGFloat(1024*1024)
        return cachSize
    }
    
    //MARK: -  changePassWordAlert
    
    func changePassWordAlert() {
        
        let alert: UIAlertController = UIAlertController.init(title: "验证原密码", message: "为保障你的数据安全，修改密码前请填写原密码。", preferredStyle: UIAlertControllerStyle.alert)
        alert.addTextField(configurationHandler: {
            (textField: UITextField!) -> Void in
            textField.placeholder = "请输入原密码"
        })
        let cancleAction = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel, handler: nil)
        let okAction = UIAlertAction.init(title: "确定", style: UIAlertActionStyle.default, handler: {
            (action: UIAlertAction!) -> Void in
            
            let password = alert.textFields?.first?.text
            if password == getUserPojo().userpassword {
                let changePassword = ChangePWDViewController()
                changePassword.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(changePassword, animated: true)
            }else{
                let alert: UIAlertController = UIAlertController.init(title: nil, message: "密码错误，请重新输入。\n如果忘记密码，请联系学校管理员。", preferredStyle: UIAlertControllerStyle.alert)
                let cancleAction = UIAlertAction.init(title: "知道了", style: UIAlertActionStyle.cancel, handler: nil)
                alert.addAction(cancleAction)
                self.present(alert, animated: true, completion: nil)
                
            }
        })
        alert.addAction(cancleAction)
        alert.addAction(okAction)
        self.present(alert, animated: true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
